# 导入所需的调度器类和触发器类
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime
from pytz import timezone
from threading import RLock

lock = RLock()

def _task_print():
    print('5秒',datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'))

def task_test():
    print('10秒',datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'))


class _SchedulerManage(BackgroundScheduler):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance:
            return cls._instance
        with lock:
            if cls._instance:
               return cls._instance
            cls._instance = super().__new__(cls)
            return cls._instance

    def __init__(self):
        super().__init__()
        # 1、设置时区
        self.configure(timezone=timezone('Asia/Shanghai'))
        # 2、使用内存存储定时任务信息
        jobstore_memory = MemoryJobStore()
        self.add_jobstore(jobstore_memory)
        # 3、添加任务
        self.add_task()

    def add_task(self):
        self.add_job(_task_print, 'interval', seconds = 5,id='_task_print', replace_existing=True)
        self.add_job(task_test,  'interval', seconds = 10, id='task_test', replace_existing=True)
    def __call__(self, *args, **kwargs):

        #启动定时任务
        self.start()

SchedulerManage = _SchedulerManage()
if __name__ == '__main__':
    #启动
    SchedulerManage()
